package com.carpedil.es.service.impl;

import com.carpedil.es.entity.SourceCodeEntity;
import com.carpedil.es.entity.UrlEntity;
import com.carpedil.es.mapper.SourceCodeMapper;
import com.carpedil.es.service.UrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

/** @author Administrator */
@Service
public class ElasticSearchService {
  @Autowired RestTemplate restTemplate;
  @Autowired UrlService urlService;
  @Autowired SourceCodeMapper sourceCodeMapper;

  @Scheduled(cron = "*/25 * * * * MON-FRI")
  public void activateService() {
    // 得到所有url
    List<UrlEntity> urlList = urlService.getUrlList();
    for (UrlEntity url : urlList) {
      SourceCodeEntity codeEntity = new SourceCodeEntity();
      // 获取源码
      String body = restTemplate.getForEntity(url.getSourceUrl(), String.class).getBody();
      // 封装数据
      codeEntity.setSid(String.valueOf(UUID.randomUUID()));
      codeEntity.setSourceCodes(body);
      codeEntity.setSourceUrl(url.getSourceUrl());
      System.out.println("body = " + body);
      // 保存到es数据库中
      sourceCodeMapper.save(codeEntity);
    }
  }
}
